﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBatisNet.DataMapper;
using Nextworks.Core.Services;

namespace Nextworks.Core.Plugin
{
    internal class PluginService : IPluginService
    {
        private IDictionary<string, Plugin> _dataObjectPluginMap = new Dictionary<string, Plugin>();
        private PluginCollection _plugins = new PluginCollection();

        public PluginService()
        {
            RegisterPlugin(CreateCorePlugin());
        }

        //Use this for now to load core plugin until we have plugin loader set up
        private Plugin CreateCorePlugin()
        {
            Plugin core = new Plugin()
            {
                Info = new PluginInfo() { Id = Guid.NewGuid(), Name = "core", Version = 0 },
                Mapper = ServiceContainer.Instance.Resolve<ISqlMapper>("coreSqlMap")
            };

            core.DataObjects.Add(new PluginDataObject() { ObjectKey = "user", ObjectType = typeof(User), Plugin = core });

            return core;
        }

        public void RegisterPlugin(Plugin plugin)
        {
            _plugins.Add(plugin);
            foreach (PluginDataObject dataObj in plugin.DataObjects)
            {
                _dataObjectPluginMap.Add(dataObj.ObjectKey, plugin);
            }
        }

        public PluginDataObject GetObject(string objectType)
        {
            if (_dataObjectPluginMap.ContainsKey(objectType))
            {
                return _dataObjectPluginMap[objectType].DataObjects[objectType];
            }
            else
            {
                throw new TypeLoadException("Type key \"" + objectType + "\" not registered");
            }
        }
    }
}
